<?php

namespace app\middleware;

use Webman\Http\Request;
use Webman\Http\Response;

class AccessControl implements \Webman\MiddlewareInterface
{

    /**
     * @inheritDoc
     */
    public function process(Request $request, callable $handler): Response
    {
        /** @var Response $response */
        if ($request->method() == 'OPTIONS') {
            $response = response('');
        } else {
            $response = $handler($request);
        }
        $response->withHeaders([
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Allow-Origin' => $request->header('origin', '*'),
            'Access-Control-Allow-Methods' => $request->header('access-control-request-method', '*'),
            'Access-Control-Allow-Headers' => $request->header('access-control-request-headers', '*'),
        ]);
        return $response;
    }
}